package com.jinchengll.xigua.ui.fragment;

import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.jinchengll.xigua.R;
import com.jinchengll.xigua.ui.base.BaseFragment;
import com.jinchengll.xigua.ui.viewmodel.HomeViewModel;

import java.util.ArrayList;
import java.util.List;

// 主页Fragment
public class HomeFragment extends BaseFragment {

    private final String LOG_TAG = "HomeFragment";

    private HomeViewModel viewModel;

    private ViewPager2 viewPager;
    private TabLayout tabLayout;

    public HomeFragment() {
    }

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected void initData() {
        Log.d(LOG_TAG, "创建");
        viewModel.items.observe(this, this::initTabAndPager);
        viewModel.getItems();
    }

    // 根据列表信息初始化TabLayout和ViewPager
    private void initTabAndPager(List<String> items) {
        List<Fragment> fragments = new ArrayList<>(items.size());
        for (String item : items) {
//            tabLayout.addTab(tabLayout.newTab().setText(item));
            if ("推荐".equals(item)) {
                fragments.add(RecommendFragment.newInstance());
            } else if ("直播".equals(item)) {
                fragments.add(DiffviewFragment.newInstance());
            } else {
                fragments.add(BlankFragment.newInstance(item));
            }
        }
        viewPager.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragments.get(position);
            }

            @Override
            public int getItemCount() {
                return fragments.size();
            }
        });
        viewPager.setCurrentItem(1);
        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager,
                (tab, position) -> tab.setText(items.get(position)));
        tabLayoutMediator.attach();
    }


    @Override
    protected void initView(View view) {
        viewModel = getViewModel(HomeViewModel.class);
        viewPager = view.findViewById(R.id.testViewPage2);
        tabLayout = view.findViewById(R.id.testTabLayout);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void onDestroy() {
        Log.d(LOG_TAG, "onDestroy");
        super.onDestroy();
    }
}